require "gd"

local from,to,fmt,outfile = ...
assert(outfile,"four params expected")
local imgs = {}
local w,h
for i=tonumber(from),tonumber(to) do
	local img = assert(gd.createFromPng(fmt:format(i)),"Could not open "..fmt:format(i))
	imgs[i-from+1] = img
	local ww,hh = img:sizeXY()
	assert(not w or (ww == w and hh == h), "Image size mismatch in "..fmt:format(i))
	w,h = ww,hh
end

local cols = math.ceil(1024/w)
local rows = math.ceil(#imgs/cols)
local ow,oh = w*cols,rows*h
local out = gd.createTrueColor(ow,oh)
out:saveAlpha(true)
out:alphaBlending(false)
local orig = imgs[1]
out:filledRectangle(0,0,ow,oh,out:colorAllocateAlpha(0,0,255,127))
out:copy(orig,0,0,0,0,w,h)

for i=2,#imgs do
	local col = (i-1)%cols
	local row = ((i-1)-col)/cols
	local img = imgs[i]
	local function pxcp (x,y)
		local c = img:getPixel(x,y)
		local alpha = img:alpha(c)
		if alpha >= 126 then return end
		local o = orig:getPixel(x,y)
		if o == c then return end
		local cr,cg,cb,ca = img:red(c),img:green(c),img:blue(c),img:alpha(c)
		local ro,go,bo,oa = orig:red(o),orig:green(o),orig:blue(o),orig:alpha(o)
		local dr,dg,db,da = ro-cr,go-cg,bo-cb,oa-ca
		local thres = dr*dr+dg*dg+db*db+da*da
		if thres < 32 then return end
		out:setPixel(col*w+x,row*h+y,c)
	end
	for x=0,w-1 do
		for y=0,h-1 do
			pxcp(x,y)
		end
	end
end

out:png(outfile)
